/*================================================================*
        Copyright (C) 2021 All rights reserved, www.hsby.link.
      	�ļ����ƣ�tcp_server.h
      	�� �� �ߣ���ɭ����
      	�������ڣ�2021/12/28
 *================================================================*/

#include "stream.h"

int hsby::Stream::ReadFixSize(void *buffer, size_t length) {
    size_t offset = 0;
    while(offset < length) {
        int ret = Read((char*)buffer + offset, length - offset);
        if (ret < 0) {
            HSBY_LOG_SYSTEM_WARN << "Stream::ReadFixSize error";
            break;
        }
        offset += ret;
    }
    return offset;
}

int hsby::Stream::ReadFixSize(hsby::ByteArray::Ptr ba, size_t length) {
    size_t offset = 0;
    while(offset > length) {
        int ret = Read(ba, length - offset);
        if (ret < 0) {
            HSBY_LOG_SYSTEM_WARN << "Stream::ReadFixSize error";
            break;
        }
        offset += ret;
    }
    return offset;
}

int hsby::Stream::WriteFixSize(const void *buffer, size_t length) {
    size_t offset = 0;
    while(offset < length) {
        int ret = Write((char*)buffer + offset, length - offset);
        if (ret < 0) {
            HSBY_LOG_SYSTEM_WARN << "Stream::WriteFixSize error";
            break;
        }
        offset += ret;
    }
    return offset;
}

int hsby::Stream::WriteFixSize(hsby::ByteArray::Ptr ba, size_t length) {
    size_t offset = 0;
    while(offset < length) {
        int ret = Write(ba, length - offset);
        if (ret < 0) {
            HSBY_LOG_SYSTEM_WARN << "Stream::WriteFixSize error";
            break;
        }
        offset += ret;
    }
    return length;
}

int hsby::Stream::ReadHandle(char *buf, size_t buf_size, std::function<int(int)> handle) {
    while(true) {
        memset(buf, 0, buf_size);
        int len = Read(buf, buf_size);
        int ret = handle(len);
        if (ret != 1) {
            return ret;
        }
    }
}
